/**
 * 
 */
package reco.db.validation;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Arrays;
import java.util.Collection;

import reco.db.Constraint;

/**
 * @author juanjo
 */
public class NotInConstraint<T> extends Constraint<T> {

    private final Object[] elements;
    private Object[] errorArguments;

    public NotInConstraint(Collection<? extends T> notInElements) {
        super("notIn", "notPermitedValue");
        checkNotNull(notInElements, "notInElements");
        checkArgument(!notInElements.isEmpty(), "notInElements can not be empty");
        this.elements = notInElements.toArray();
    }

    public NotInConstraint(T... notInElements) {
        super("notIn", "notPermitedValue");
        checkNotNull(notInElements, "notInElements");
        checkArgument(notInElements.length > 0, "notInElements can not be empty");
        this.elements = notInElements.clone();
    }

    @Override
    public boolean validate(T value) {
        if (value == null) {
            return true;
        }

        for (final Object element : this.elements) {
            if (value.equals(element)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object[] getErrorArguments() {
        if (this.errorArguments == null) {
            this.errorArguments = new Object[] { Arrays.asList(this.elements) };
        }
        return this.errorArguments;
    }

}
